﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using BaiduMapPOI;
using System.Text.RegularExpressions;
using System.Threading;

namespace BaiduMapAddressUpdate
{
    public partial class MainForm : Form
    {
        SqlOP sqlOP = new SqlOP(BaiduMapAddressUpdate.Properties.Settings.Default.conn);
        string suid = "";
        string cX = "";
        string cY = "";
        int id = 0;
        int k = 0;

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = false;
            Thread thread = new Thread(new ThreadStart(Start));
            thread.Start();
        }

        void Start()
        {
            string name = "";
            sqlOP.db.Open();
            DataTable dt = sqlOP.Select("id,name,uid,pointX,pointY", "POI", "");
            
            foreach (DataRow dr in dt.Rows)
            {
                id = Convert.ToInt32(dr["id"].ToString().Trim());
                name = dr["name"].ToString().Trim();
                suid = dr["uid"].ToString().Trim();
                cX = dr["pointX"].ToString().Remove(dr["pointX"].ToString().Length - 4);
                cY = dr["pointY"].ToString().Remove(dr["pointY"].ToString().Length - 4);
                string url = "http://map.baidu.com/?newmap=1&qt=s&wd=" + HttpUtility.UrlEncode(name) + "&c=332";
                
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    int count = dt.Rows.Count;
                    this.liMessage.Items.Add("正在更新:" + name);
                    this.progressBar.Minimum = 0;
                    this.progressBar.Maximum = count;
                    this.progressBar.Step = 1;
                    this.progressBar.PerformStep();
                    this.lbResult.Text = string.Format("当前位置：{0}/{1}", k, count);
                });

                try
                {
                    AddInfo(url);
                }
                catch (Exception ex)
                {
                    sqlOP.Insert("x,y,cause,time", "log", "'" + cX + "','" + cY + "','" + ex.ToString() + "','" + DateTime.Now.ToString() + "'");
                }
            }

            sqlOP.DeleteRepeat("uid", "Address", "id");
            sqlOP.db.Close();

            this.BeginInvoke((MethodInvoker)delegate()
            {
                MessageBox.Show("信息更新完成！");
                this.btnStart.Enabled = true;
            });
        }

        void AddInfo(string url)
        {
            string info = StringProcess.ToGB2312(StringProcess.GetResult(url, Encoding.UTF8)).Replace("\"","").Replace("\\","");
            string content = Regex.Match(info, "(?<=(content:\\[))[\\S\\s]*?(?=(\\],current_city))").Value + "]],";
            
            MatchCollection mcList = Regex.Matches(content, "(?<=(cp:))[\\S\\s]*?(?=(\\]\\],))");

            for (int i = 0; i < mcList.Count; i++)
            {
                string uid = Regex.Match(mcList[i].Value, "(?<=(,uid:))[\\S\\s]*?(?=(}))").Value;
                string address = Regex.Match(mcList[i].Value, "(?<=(addr:))[\\S\\s]*?(?=(,))").Value;
                string point = Regex.Match(mcList[i].Value, "(?<=(geo:1\\|))[\\S\\s]*?(?=(;))").Value + ",";
                string x = Regex.Match(point, "(?<=())[\\S\\s]*?(?=(,))").Value;
                string y = Regex.Match(point, "(?<=(,))[\\S\\s]*?(?=(,))").Value;

                if (uid.Trim() == suid || (x.Trim() == cX && y.Trim() == cY))
                {
                    sqlOP.Insert("id,address,uid", "Address", "'" + id.ToString() + "','" + address + "','" + uid + "'");
                }
                else
                {
                    sqlOP.Insert("x,y,cause,time", "log", "'" + x + "','" + y + "','Add','" + DateTime.Now.ToString() + "'");
                }
            }

            ++k;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            sqlOP.db.Open();
            DataTable dtLog = sqlOP.Select("id,x,y", "log", "(cause = N'Add')");
            MessageBox.Show(dtLog.Rows.Count.ToString());
            foreach (DataRow rowLog in dtLog.Rows)
            {
                string id = rowLog["id"].ToString();
                string x = rowLog["x"].ToString();
                string y = rowLog["y"].ToString();
                DataTable dtPoint = sqlOP.Select("id", "POI", "(pointX = N'" + x + "0000') AND (pointY = N'" + y + "0000')");

                if (dtPoint.Rows.Count != 0)
                {
                    sqlOP.Delete("log", "(id = " + id + ")");
                }
            }
            sqlOP.db.Close();
            MessageBox.Show("完成！");
        }

    }
}
